#include "muduo/proto/codec.h"
#include "muduo/proto/dispatcher.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/net/TcpClient.h"
#include "muduo/base/CountDownLatch.h"

#include "request.pb.h"

#include <iostream>

class Client
{
public:
    typedef std::shared_ptr<google::protobuf::Message> MassagePtr;
    typedef std::shared_ptr<req::TranslateResponse> TranslateResponsePtr;
    typedef std::shared_ptr<req::AddResponse> AddResponsePtr;
    Client(const std::string &sip, int sport)
        :_latch(1),
        _client(_loop.startLoop(), muduo::net::InetAddress(sip, sport), "Client"),
        _dispatcher(std::bind(&Client::onUnknownMessage, this,
                                             std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
        _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher,
                                        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 注册业务处理函数
        _dispatcher.registerMessageCallback<req::TranslateResponse>(std::bind(&Client::onTranslate, this,
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<req::AddResponse>(std::bind(&Client::onAdd, this,
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        // 设置client收到数据后的消息处理回调(这里是解析数据, 然后根据数据进行分发任务)
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _client.setConnectionCallback(std::bind(&Client::onConnection, this, std::placeholders::_1));
    }
    // 连接服务器
    void connect()
    {
        _client.connect();
        _latch.wait();
    }
    void Translate(const std::string &msg)
    {
        req::TranslateRequest req;
        req.set_req(msg);
        // 发送消息
        Send(req);
    }
    void Add(int x, int y)
    {
        req::AddRequest add_req;
        add_req.set_num1(x);
        add_req.set_num2(y);
        Send(add_req);
    }
private:
    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn,
                          const MessagePtr &message,
                          muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }
    bool Send(const google::protobuf::Message &message)
    {
        if(_conn->connected())
        {
            _codec.send(_conn, message);
            return true;
        }
        return false;
    }

    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateResponsePtr &message, muduo::Timestamp)
    {
        std::cout << "翻译结果：" << message->resp() << std::endl;
    }
    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddResponsePtr &message, muduo::Timestamp)
    {
        std::cout << "计算结果：" << message->result() << std::endl;
    }
    // 客户端这里需要在这里进行同步控制
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected()) 
        {
            _latch.countDown();
            _conn = conn;
        }
        else // 连接关闭
        {
            _conn.reset();
        }
    }

private:
    muduo::net::EventLoopThread _loop; // EventLoopThread对象在实例化完成之后直接就开始监控, 不需要我们自己去启动
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _latch; // 内部使用条件变量进行同步控制
    ProtobufCodec _codec; // 协议处理
    ProtobufDispatcher _dispatcher; // 任务派发
};

int main()
{
    Client client("127.0.0.1", 8888);

    client.connect();

    client.Add(11, 22);
    client.Translate("hello");

    sleep(3);

    return 0;
}